<script>
import { computed, defineComponent } from 'vue';
import FanLoading from '../loading/loading.vue';
import { createNamespace, transformSize, transformStyleSize } from '../utils';
import { ListStatus } from '../config'
import { usePageLifecycle } from '../hooks';

export default defineComponent({
  name: createNamespace('List')[0],
  options: {
    // https://uniapp.dcloud.io/matter.html#mp
    virtualHost: true,
  },
  components: { FanLoading },
  props: {
    /**
     * 是否处于隐藏状态，此时不触发触底
     */
    hidden: {
      type: Boolean,
      default: false,
    },
    status: {
      type: String,
      default: 'loading',
      validator: (value) => {
        return ['loading', 'hasMore', 'noMore', 'error'].includes(value);
      },
    },
    loadingColor: String,
    loadingSize: {
      type: Number,
      default: 22,
    },
    loadingText: {
      type: String,
      default: '',
    },
    textColor: {
      type: String,
      default: '#999',
    },
    noMoreText: {
      type: String,
      default: '没有更多了',
    },
    errorText: {
      type: String,
      default: '加载失败',
    },
  },
  emits: ['load', 'errorClick'],
  setup(props, context) {
    const text = computed(() => {
      const { loadingText, noMoreText, errorText, status } = props;
      if (status === ListStatus.noMore) return noMoreText;
      if (status === ListStatus.error) return errorText;
      return loadingText;
    });
    const textSize = computed(() => {
      return `calc(${transformSize(props.loadingSize)} * 0.64)`;
    });
    const showLoading = computed(() => {
      return props.status === ListStatus.loading || props.status === ListStatus.hasMore;
    });

    const { onPageReachBottom } = usePageLifecycle();
    onPageReachBottom(() => {
      !props.hidden && context.emit('load');
    });

    const onErrorClick = () => {
      if (props.status !== ListStatus.error) return;
      context.emit('errorClick');
    };

    return { text, textSize, showLoading, onErrorClick };
  },
});
</script>

<template>
  <div class="fan-list">
    <slot />

    <div v-if="showLoading || text" @click="onErrorClick"
      class="fan-flex fan-align-center fan-justify-center fan-list__load"
      :style="{ fontSize: textSize, color: textColor }">
      <FanLoading v-if="showLoading" :size="loadingSize" :color="loadingColor" />
      <span class="fan-list__loadt">{{ text }}</span>
    </div>
  </div>
</template>

<style lang="less">
.fan-list {
  box-sizing: border-box;

  &__loadt {
    display: inline-block;
    vertical-align: middle;
  }

  &__load {
    padding: 10px 0;
    font-size: 14px;
    color: #999;
  }
}
</style>
